import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router";
import {
  busLineDetail,
  stopListQuery,
  orderAdd,
  pay,
} from "../../service/busService";
import {
  NavBar,
  Button,
  Toast,
  Popup,
  Picker,
  Dialog,
  Radio,
} from "antd-mobile";
import "./bus.scss";
interface DataList {
  startTime: string;
  first: string;
  name: string;
  endTime: string;
  end: string;
  price: string;
  mileage: string;
}
export default function BusDetail() {
  let location = useLocation();
  let navigate = useNavigate();
  let [detailList, setDetailList] = useState({} as DataList);
  let [stopList, setStopList] = useState(
    [] as {
      name: string;
      stepsId: string;
    }[]
  );
  let busId = location.pathname.split("detail/")[1];
  let [station, setStation] = useState("");
  // let [code, setCode] = useState('')
  const [visible, setVisible] = useState(false);
  let [startname, setStartname] = useState("");
  let [startnameValue, setStartnameValue] = useState<(string | null)[]>([]);
  let [endname, setEndname] = useState("");
  let [startFlag, setStartFlag] = useState(false);
  let [endColumnsValue, setEndColumnsValue] = useState<(string | null)[]>([]);
  let [columns, setColumns] = useState<any[]>([]);
  let onClose = () => setStation("");

  useEffect(() => {
    (async () => {
      let res = await busLineDetail(busId);
      setDetailList(res.data.data);
    })();
  }, []);

  useEffect(() => {
    (async () => {
      let res = await stopListQuery({ linesId: busId });
      setStopList(res.data.rows);
      const columns = res.data.rows.map((item: any) => {
        return {
          label: item.name,
          value: item.stepsId + "",
        };
      });
      console.log(columns, "24324");

      setColumns([columns]);
    })();
  }, []);

  // console.log(columns);
  return (
    <div
      style={{
        position: "fixed",
        top: "0px",
        bottom: "0px",
        left: "0px",
        right: "0px",
        backgroundColor: "#f6f6f6",
        overflow: "scroll",
        zIndex: "1",
      }}
    >
      <NavBar
        onBack={() => navigate(-1)}
        right={
          <div onClick={() => navigate("/bus_query/ticket")}>我的车票</div>
        }
      >
        路线详情
      </NavBar>
      <div className="busline-box">
        <div className="busline-detailList">
          <div className="busline-top">
            <div className="busline-left" onClick={() => setStation("start")}>
              <div className="busline-time">{detailList.startTime}</div>
              <div className="busline-time">{startname}</div>
              <div className="busline-start_address">
                <span>始发</span>
                {detailList.first}
                {/* {detailList.first}--{startname} */}
                {/* {!startFlag?{detailList.first}:{startname}} */}
              </div>
            </div>
            <div className="busline-middle">
              <div className="busline-bos_id">{detailList.name}</div>
            </div>
            <div className="busline-right" onClick={() => setStation("end")}>
              <div className="busline-time">{detailList.endTime}</div>
              <div className="busline-time">{endname}</div>
              <div className="busline-end_address">
                <span>终点</span>
                {detailList.end}
              </div>
            </div>
          </div>
          <div className="busline-bottom">
            <div className="busline-li">
              票价：<span>{detailList.price}</span>
            </div>
            <div className="busline-li">
              里程：<span>{detailList.mileage}</span>
            </div>
          </div>
          <div
            className="btn-buy"
            style={{ marginTop: "10px", width: "50%", margin: "10px auto" }}
          >
            <Button
              color="primary"
              shape="rounded"
              block
              onClick={async () => {
                if (!startname)
                  return Toast.show({
                    icon: "fail",
                    content: "请选择起点站",
                  });
                if (!endname)
                  return Toast.show({
                    icon: "fail",
                    content: "请选择终点站",
                  });
                let orderRes = await orderAdd({
                  start: startname,
                  end: endname,
                  price: detailList.price,
                  path: detailList.name,
                  status: 1,
                });

                console.log(orderRes);
                if (orderRes.data.code === 200) {
                  let order_id = orderRes.data.orderNum;
                  Dialog.confirm({
                    title: "请选择支付方式",
                    content: (
                      <Radio.Group defaultValue="r1">
                        <Radio value="r1">支付宝</Radio>
                        <Radio value="r2">微信</Radio>
                      </Radio.Group>
                    ),
                    onConfirm() {
                      Dialog.confirm({
                        content: (
                          <div
                            style={{
                              display: "flex",
                              alignContent: "center",
                              justifyContent: "center",
                            }}
                          >
                            <img
                              src="https://img.atobo.com/ProductImg/EWM/UWeb/1/4/6/4/750/1464750/1.gif"
                              alt="二维码"
                            />
                          </div>
                        ),
                        confirmText: "我已支付",
                        async onConfirm() {
                          let res = await pay({
                            orderNum: order_id,
                            paymentType: "电子支付",
                          });
                          console.log(res, 'res');

                          if (res.data.code === 200) {
                            Toast.show({
                              icon: "success",
                              content: "购票成功!",
                            });
                            navigate("/bus_query/ticket?type=2");
                          }
                        },
                        onCancel() {
                          navigate("/bus_query/ticket?type=1");
                        },
                      });
                    },
                  });
                } else {
                  Toast.show({
                    icon: "fail",
                    content: "请选择起点站和终点站!",
                  });
                  setStation("start");
                }
              }}
            >
              立即购票
            </Button>

            {/* <Button type='primary' block round onClick={() =>
            Dialog.confirm({
              title: '请选择支付方式',
              // message: <div>支付宝</div>,
              message: <div>
                <Radio.Group direction='horizontal' >
                  <Radio name='r1'>支付宝</Radio>
                  <Radio name='r2'>微信</Radio>
                </Radio.Group>
              </div>,
            })
              .then( async() => {
                // setVisible(true)                
                // console.log('confirm')
              })
              .catch(() => {
                // console.log('catch')
              })
          }>
            立即购票
          </Button> */}
          </div>
        </div>

        <div className="route-box">
          <div className="route-title">路线详情</div>
          <div className="route_region">
            <div className="route-left">
              <img
                src="https://img0.baidu.com/it/u=995930361,2720222055&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                alt="火车"
              />
            </div>
            <div className="route-middle">
              <div className="route-start"></div>
              {stopList
                .slice(1, stopList.length - 1)
                .map((item: any, index) => {
                  return (
                    <div className="route-li" key={index}>
                      <div className="route-li_region"></div>
                    </div>
                  );
                })}

              <div className="route-end"></div>
            </div>
            <div className="route-right">
              {stopList
                .slice(1, stopList.length - 1)
                .map((item: any, index) => {
                  return (
                    <div className="route-li" key={index}>
                      {item.name}
                    </div>
                  );
                })}
              <div className="route-start">{detailList.first}</div>
              <div className="route-end"> {detailList.end}</div>
            </div>
          </div>
        </div>
      </div>

      {/* <Cell title='底部弹出' onClick={() => setState('bottom')} /> */}
      <Picker
        title="起点站"
        visible={station === "start"}
        columns={columns}
        value={startnameValue}
        onCancel={() => setStation("")}
        onConfirm={(value: any, index) => {
          columns[0].map((item: any) => {
            if (item.value === value[0]) {
              if (item.label === detailList.end) {
                return Toast.show({
                  icon: "fail",
                  content: "起点站不能是终点站,请重新选择",
                });
              } else {
                console.log(value[0], item);

                setStartnameValue([value[0] + ""]);
                setStartname(item.label);
                setStation("");
              }
              //  console.log(item.text);
            }
          });
          setStartFlag(true);
        }}
      />
      <Picker
        title="终点站"
        visible={station === "end"}
        columns={columns}
        value={columns}
        onCancel={() => setStation("")}
        onConfirm={(value, index) => {
          columns[0].map((item: any) => {
            if (item.value === value[0]) {
              if (item.label === detailList.first) {
                return Toast.show({
                  icon: "fail",
                  content: "终点站不能是起点站,请重新选择",
                });
              } else {
                console.log(value[0], item);

                setEndColumnsValue([value[0] + ""]);
                setEndname(item.label);
                setStation("");
              }
              //  console.log(item.text);
            }
          });
          setStartFlag(true);
        }}
      />

      <Popup visible={visible} onClose={() => setVisible(false)}>
        <div style={{ padding: "30px 50px" }}>
          <img
            src="https://img.atobo.com/ProductImg/EWM/UWeb/1/4/6/4/750/1464750/1.gif"
            alt="二维码"
          />
        </div>
      </Popup>
    </div>
  );
}
